#!/bin/sh

function mount_ubifs() {
    local ubi_num=$1
    local mtd_num=$2
    local mount_point=$3
    local vol_name=$4
    local vol_size=$5
    
    # 附加MTD设备到UBI
    ubiattach /dev/ubi_ctrl -m ${mtd_num}
    if [ $? -ne 0 ]; then
        echo "ubiattach failed for mtd${mtd_num}!"
        return 1
    fi
    
    # 创建卷
    ubimkvol /dev/ubi${ubi_num} -s ${vol_size} -N ${vol_name}
    
    # 挂载UBI卷
    mount -t ubifs ubi${ubi_num}_0 ${mount_point}
    
    if [ $? -ne 0 ]; then
        echo "${mount_point} mount fail!"
        sync
        
        flash_erase /dev/mtd${mtd_num} 0 0
        ubidetach -m ${mtd_num}
        ubiattach /dev/ubi_ctrl -m ${mtd_num}
        ubimkvol /dev/ubi${ubi_num} -s ${vol_size} -N ${vol_name}
        mount -t ubifs ubi${ubi_num}_0 ${mount_point}
        
        if [ $? -ne 0 ]; then
            echo "Mount failed after retry!"
            return 1
        fi
    fi
    
    echo "Mount ${mount_point} success"
    return 0
}

function start() {
    mount -t squashfs /dev/mtdblock4 /app
    if [ $? -eq 0 ];then
        echo "mount app success!"
    else
        echo "mount app failed!"
    fi
    
    # Mount config partition (mtd5) - 10M，使用ubi0
    mount_ubifs 0 5 "/mnt/config" "config" "7110656"
    echo "mount config done"
    
    # Mount log partition (mtd6) - 10M，使用ubi1
    mount_ubifs 1 6 "/mnt/log" "log" "7110656"
    echo "mount log done"
    
    # Mount data partition (mtd7) - 10M，使用ubi2
    mount_ubifs 2 7 "/mnt/data" "data" "7110656"
    echo "mount data done"
    
    echo "Starting App"
    /app/startapp.sh
}

function stop() {
    echo "Stopping App"
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart|reload)
        stop
        start
    ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?